package com.mayuanfei.springboot12.controller;

import cn.hutool.json.JSONUtil;
import com.hazelcast.core.HazelcastInstance;
import com.mayuanfei.springboot12.common.Constants;
import com.mayuanfei.springboot12.pojo.UserInfo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 用户缓存测试
 *
 * @author 老马
 * @date 2023-07-10 16:23
 */
@RestController
public class UserCacheTestController {

    @Resource
    private HazelcastInstance hazelcastInstance;

    @PostMapping(value = "/writeuser")
    public String writeDataToHazelcast(String userId, String userName) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setUserName(userName);
        Map<String, Object> hazelcastMap = hazelcastInstance.getMap(Constants.CACHE_NAME_SESSION_USERS);
        hazelcastMap.put(userId, userInfo);
        return "Map数据写入完成" + JSONUtil.toJsonStr(hazelcastMap.get(userId));
    }

    @GetMapping(value = "/readoneuser")
    //@Cacheable(cacheNames = "session:users", key = "#userId", condition = "#userId != null")
    public UserInfo readDataFromHazelcast(String userId) {
        Map<String, Object> hazelcastMap = hazelcastInstance.getMap(Constants.CACHE_NAME_SESSION_USERS);
        return (UserInfo) hazelcastMap.get(userId);
    }

    @GetMapping(value = "/readalluser")
    public Map<String, Object> readAllDataFromHazelcast() {
        return hazelcastInstance.getMap(Constants.CACHE_NAME_SESSION_USERS);
    }

}